<?php

namespace app\controller\admin;

use app\BaseController;
use app\model\admin\ApplyPay;
use EasyWeChat\Factory;

class AdminBaseController extends BaseController
{
    protected $model;
    //当前访问的用户
    protected $uid = 0;
    //当前页码
    protected $page;
    //分页变量名称
    protected $pageVar;
    //每页数据量
    protected $limit;
    //用户信息
    protected $userInfo;
    // 初始化
    protected function initialize()
    {
        parent::initialize();
        $this->page = $this->request->get('pageNum', 1);
        $this->limit = $this->request->get('pageSize', 10);
        $this->uid    = $this->request->uid ?? 0;
        $this->userInfo    = $this->request->userInfo ?? null;
        //limit防止过大处理
        $this->limit = $this->limit <= 100 ? $this->limit : 100;
        $this->pageVar = 'pageNum';
    }
    // 根据sus_user_id获取微信支付实例
    public function getPayInstanceByAppid($sys_user_id)
    {
        $res = [
            "enabled" => false,
            "msg" => '',
            "instance" => null
        ];
        $payInfo = ApplyPay::find(1);

        if (!$payInfo) {
            storage_log("111" . json_encode($payInfo));
            // 禁用状态
            $res['enabled'] = false;
            $res['msg'] = '没有可用的微信打款配置，请先至[公众号管理->配置相关->提现打款]完成配置，或者选择手动打款！';
            $res['instance'] = null;
            return $res;
        }

        $payParams = [
            'app_id' => $this->miniInfo['appid'],
            'mch_id' => $payInfo->merchant_id,
            'key' => $payInfo->merchant_key,
            'cert_path' => app()->getRootPath() . "payFile/{$payInfo->cert_file}",
            'key_path' =>  app()->getRootPath() . "payFile/{$payInfo->key_file}",
            // 'notify_url' => $notify_url
        ];
        storage_log('提现支付配置参数' . json_encode($payParams));
        try {
            $app = Factory::payment($payParams);
        } catch (\Exception $e) {
            storage_log('提现支付配置参数' . json_encode($e));
            $res['msg'] = 'error' . $e->getMessage();
            $res['enabled'] = false;
            return $res;
        }
        $res['enabled'] = true;
        $res['msg'] = 'success';
        $res['instance'] = $app;
        return $res;
    }
}
